package ug.co.icom.kyazze.healthticket.mongoHQ;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import com.mongodb.BasicDBList;
import com.mongodb.DBObject;

import ug.co.icom.kyazze.healthticket.data.MinUser;
import ug.co.icom.kyazze.healthticket.data.QueryBuilder;
import android.os.AsyncTask;

public class MongoHQConnectionSearch extends
AsyncTask<String, Void, ArrayList<MinUser>> {

	static String server_output = null;
	static String temp_output = null;
	static ArrayList<MinUser> users = new ArrayList<MinUser>();

	@Override
	protected ArrayList<MinUser> doInBackground(String... arg0) {
		String query = arg0[0];
		QueryBuilder qb = new QueryBuilder();
		URL url;
		try {
			url = new URL(qb.buildSearchConnectionUrl(query));
			HttpURLConnection conn = (HttpURLConnection) url
					.openConnection();
			conn.setRequestMethod("GET");
			conn.setRequestProperty("Accept", "application/json");

			if (conn.getResponseCode() > 204) {
				throw new RuntimeException();
			}
			BufferedReader br = new BufferedReader(new InputStreamReader(
					(conn.getInputStream())));

			while ((temp_output = br.readLine()) != null) {
				server_output = temp_output;
			}		
			// Remove square brackets
			//OriginalObject = server_output.substring(1, server_output.length() - 1);
			BasicDBList dblist = (BasicDBList) com.mongodb.util.JSON.parse(server_output);

			for(Object ob: dblist)
			{
				DBObject userObj = (DBObject) ob;

				MinUser temp = new MinUser();

				temp.ID = userObj.get("_id").toString();
				temp.FirstName = userObj.get("firstname").toString();
				temp.LastName = userObj.get("lastname").toString();
				temp.OtherNames = userObj.get("othernames").toString();

				users.add(temp);		

			}
		} catch (Exception e) {	
			throw new RuntimeException();
		}
		return users;
	}

	@Override
	protected void onPostExecute(ArrayList<MinUser> result) {
		super.onPostExecute(result);
	}

}
